/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.clustertask.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.util.HttpUtil;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.hontu.issued.request.PageQueryRequest;
import vip.xiaonuo.hontu.issued.request.TaskDetailQueryRequest;
import vip.xiaonuo.hontu.issued.response.*;
import vip.xiaonuo.hontu.issued.util.HT_DEVICE_POST;
import vip.xiaonuo.hontu.issued.util.HongTuRequestUrl;
import vip.xiaonuo.hontu.listener.handle.model.HongTuPushData;
import vip.xiaonuo.modular.clustertask.entity.ClusterTask;
import vip.xiaonuo.modular.clustertask.param.ClusterTaskParam;
import vip.xiaonuo.modular.clustertask.service.ClusterTaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 平台下属设备service接口实现类
 *
 * @author Joe
 * @date 2023-05-25 13:44:05
 */
@Service
public class ClusterTaskServiceImpl implements ClusterTaskService {

    private final String TASK_PRE = "HT_CLUSTER_TASK_";

    @Resource
    private RedissonClient client;

    @Resource
    private DeviceBaseService deviceService;

    @Override
    public List<ClusterTask> list(ClusterTaskParam clusterTaskParam) {
        String key = TASK_PRE + clusterTaskParam.getDeviceId();
        RBucket<List<ClusterTask>> bucket = client.getBucket(key);
        try{
            if(!bucket.isExists()){
                syncTask(deviceService.getById(clusterTaskParam.getDeviceId()));
            }
        }catch (Exception e){
            throw e;
        }
        return bucket.get();
    }

    @Override
    public void syncTask(DeviceBase device) {
        if(ObjectUtil.isNull(device)){
            throw new ServiceException(500,"设备不存在");
        }
        if(ObjectUtil.notEqual( device.getDeviceState(),"1")){
            throw new ServiceException(500,"设备不在线");
        }
        String key = TASK_PRE + device.getId();
        RBucket<List<ClusterTask>> bucket = client.getBucket(key);
        List<String> existTaskUuid = new ArrayList<>();
        if(bucket.isExists()){
            List<ClusterTask> existTask = bucket.get();
            existTaskUuid = existTask.stream().map(ClusterTask::getUuid).collect(Collectors.toList());
        }
        PageQueryRequest request = new PageQueryRequest();
        List<ClusterTask> tasks = new ArrayList<>();
        int total = -1;
        try {
            while(tasks.size() != total){
                ClusterTaskListResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_CLUSTER_TASK_QUERY , device.getCabinetIp(),device.getCabinetPort(),request , ClusterTaskListResponse.class);
                if(response.getCode() == 0){ // 请求成功
                    tasks.addAll(response.getData().getList());
                    total = response.getData().getTotal();
                    request.setPageNum(request.getPageNum()+1);
                }else{
                    throw new ServiceException(response.getCode(),response.getMsg());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (ClusterTask task : tasks) {
            if(!existTaskUuid.contains(task.getUuid())){
                task.setSyncStatus(0);
            }
        }
        bucket.set(tasks);
    }

    @Override
    public void syncTaskResult(DeviceBase device) {
        if(ObjectUtil.isNull(device)){
            throw new ServiceException(500,"设备不存在");
        }

        if(ObjectUtil.notEqual( device.getDeviceState(),"1")){
            throw new ServiceException(500,"设备不在线");
        }

        String key = TASK_PRE + device.getId();
        RBucket<List<ClusterTask>> bucket = client.getBucket(key);
        if(!bucket.isExists()){
            return;
        }
        List<ClusterTask> tasks = bucket.get();
        try{
            for(ClusterTask task : tasks){
                if(ObjectUtil.equal( task.getSyncStatus(),1)){
                    continue;
                }
                List<ClusterTaskDetail> details = new ArrayList<>();
                int total = -1;
                TaskDetailQueryRequest request = new TaskDetailQueryRequest(task.getUuid());
                while(details.size()!= total){
                    ClusterTaskDetailQueryResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_CLUSTER_TASK_DETAIL_QUERY , device.getCabinetIp(),device.getCabinetPort(),request , ClusterTaskDetailQueryResponse.class);
                    if(response.getCode() == 0){ // 请求成功
                        if(response.getData().getList().isEmpty()){
                            break;
                        }
                        details.addAll(response.getData().getList());
                        total = response.getData().getTotal();
                        request.setPageNum(request.getPageNum()+1);
                    }else{
                        throw new ServiceException(response.getCode(),response.getMsg());
                    }
                }
                if(details.size()>0){
                    HongTuPushData data = new HongTuPushData();
                    data.setBusiType("99");
                    data.setData(JSON.toJSONString(details));
                    data.setDeviceId(device.getId());
                    data.setDataType(0);
                    HttpUtil.getInstance().postJsonParams("http://localhost:82/bizDataReceive",JSON.toJSONString(data));
                }
                task.setSyncStatus(1);
            }
            bucket.set(tasks);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public void syncStranger(DeviceBase device) {
        if(ObjectUtil.isNull(device)){
            throw new ServiceException(500,"设备不存在");
        }

        if(ObjectUtil.notEqual( device.getDeviceState(),"1")){
            throw new ServiceException(500,"设备不在线");
        }

        PageQueryRequest request = new PageQueryRequest();
        List<ClusterTaskDetail> details = new ArrayList<>();
        int total = -1;
        try {
            while(details.size() != total){
                ClusterTaskDetailQueryResponse response = HT_DEVICE_POST.postJson(HongTuRequestUrl.POST_STRANGER_LIST , device.getCabinetIp(),device.getCabinetPort(),request , ClusterTaskDetailQueryResponse.class);
                if(response.getCode() == 0){ // 请求成功
                    if(response.getData().getList().isEmpty()){
                        break;
                    }
                    details.addAll(response.getData().getList());
                    total = response.getData().getTotal();
                    request.addPageNum();
                }else{
                    throw new ServiceException(response.getCode(),response.getMsg());
                }
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(details.size()>0){
            HongTuPushData data = new HongTuPushData();
            data.setBusiType("99");
            data.setData(JSON.toJSONString(details));
            data.setDeviceId(device.getId());
            data.setDataType(1);
            HttpUtil.getInstance().postJsonParams("http://localhost:"+ SpringUtil.getProperty("server.port") +"/bizDataReceive",JSON.toJSONString(data));
        }

    }
}
